package com.wideplay.crosstalk.web;

import com.google.inject.Inject;
import com.wideplay.crosstalk.services.UserManager;
import com.wideplay.warp.servlet.RequestScoped;
import com.wideplay.warp.widgets.At;
import com.wideplay.warp.widgets.Post;

/**
 * This class models the login page, which is the first page every
 *  user sees. When not logged in, a user of the site is redirected
 *  here transparently by the security AOP mechanism.
 *
 * @author Dhanji R. Prasanna (dhanji@gmail.com)
 */
@At("/login") @RequestScoped
public class LoginPage {
    private String username;
    private String password;

    private String message = "";

    //service dependencies
    private final UserManager userManager;
    private final User user;

    @Inject
    public LoginPage(UserManager userManager, User user) {
        this.userManager = userManager;
        this.user = user;
    }

    @Post
    public String login() {

        //attempt to authenticate the user
        if (userManager.authenticate(username, password))
            user.login(username);
        else {
            //clear user context from session
            user.logout();

            //stay on this page with error
            return "/login?message=Bad+credentials.";
        }

        //redirect to home page if successfully logged in
        return "/home";
    }


    //getters/setters...
    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}